<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            margin: 100px auto;
            width: 300px;
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;

        }

        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }

        td {
            font: 14px "微软雅黑";
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th><input type="checkbox" id="j_cbAll"></th>
                <th>商品</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody id="j_tb">
            <tr>
                <td><input type="checkbox" name="" id=""></td>
                <td>小米</td>
                <td>2000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="" id=""></td>
                <td>红米</td>
                <td>2000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="" id=""></td>
                <td>大米</td>
                <td>2000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="" id=""></td>
                <td>中米</td>
                <td>2000</td>
            </tr>
        </tbody>
    </table>
    <script>

        var j_cbAll = document.getElementById('j_cbAll') //全选按钮 
        var j_tbs = document.getElementById('j_tb').getElementsByTagName('input')//下面所有的复选框

        //1 全选和取消全选
        j_cbAll.onclick = function () {
            // console.log(this.checked);  //拿到当前选中状态 true 就是选中 /false
            for (var i = 0; i < j_tbs.length; i++) {

                j_tbs[i].checked = this.checked;   // 赋值给当前所有的复选框
            }
        }

        2.//给下面所有复选框绑定点击事件
        for (var i = 0; i < j_tbs.length; i++) {
            j_tbs[i].onclick = function () {
                var flag = true;   //控制全选按钮是否选中

                //没次点击下面的复选框都要循环检查4个小按钮是否被选中
                for (var i = 0; i < j_tbs.length; i++) {
                    if (!j_tbs[i].checked) {         //如果里面有一个没被选中
                        flag = false;
                        break;
                    }
                }
                j_cbAll.checked = flag;

            }

        }

    </script>

</body>

</html>